// 封装请求
import axios from "axios";



// vue3 更推荐将公用模块封装成hook函数,在需要使用的组件中,,导入 hook 函数使用模块(类似于 useRoute, useRouter 等)
export const useAxios = () => {
    axios.defaults.baseURL = '/api'
    axios.interceptors.request.use(config => {
        config.headers = {
            'Content-Type': 'application/json;charset=utf-8',
            'authentication': uni.getStorageSync('token')
        }
        return config
    })

    function get(url, params) {
        return axios.get(url, { params })
    }

    function post(url, params) {
        let search = new URLSearchParams()
        for (let k in params) { search.append(k, params[k]) }
        return axios.post(url, search)
    }
	
	function put (url, data){
		return axios({
		method: 'PUT',
		url: url,
		data: data
		});
	}	
	 const del = (url, data) => {
	  return axios.delete(url,{data})
	}
    return { get,post,put,del }
}

/*
// 对uni.request()进行封装
// 设置请求拦截
import qs from 'qs'
let baseURL = '/api'
// let baseURL= '/mock'
uni.addInterceptor('request', {
	// 拦截前触发
	invoke(opt) {
		// 修改baseUrl
		opt.url = baseURL + opt.url
		// header
		
		let obj = {}
		if (opt.headers) {
			obj = opt.headers
		} else {
			obj = {
				'Content-Type': 'application/json;charset=utf-8',
			}
		}
		opt.header = {
			...obj,
			'authentication': uni.getStorageSync('token')
		}
	}
})
// method:'GET','POST','PUT','DELETE','HEAD','OPTIONS'
function get(url, data) {
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data,
			success(res) {
				resolve(res.data)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

function post(url, data) {
	data = JSON.stringify(data)
	
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data,
			method: "POST",
			success(res) {
				resolve(res.data)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}


function update(url, data, header = {}) {
	data = JSON.stringify(data)
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data,
			...header,
			method: "PUT",
			success(res) {
				resolve(res.data)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}


function del(url, data) {
	data = JSON.stringify(data)
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data,

			method: "DELETE",
			success(res) {
				resolve(res.data)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}


export default {
	get,
	post,
	update,
	del
}

*/
